<template>
  <div class="setRole-dialog">
    <base-dialog
      :model="setData.isOpen"
      @close="closeDialogHandle"
      title="分配角色"
    >
      <template #body>
        <el-form ref="form" label-width="80px">
          <el-form-item label="角色">
            <el-select v-model="userRoleList" multiple placeholder="请选择角色">
              <span v-for="(item, index) in roleList" :key="index">
                <el-option
                  :label="item.roleName"
                  :value="item.id"
                  :key="index"
                ></el-option>
              </span>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="setData.isOpen = false">取 消</el-button>
        <el-button type="primary" @click="setUserRole">确 定</el-button>
      </template>
    </base-dialog>
  </div>
</template>

<script>
import { getRoleListById, setUserRole, getRoleList } from '@/api/system'
export default {
  props: {
    setData: {
      type: Object
    }
  },
  data () {
    return {
      formData: {
        userId: '',
        roleIdList: []
      },
      queryInfo: {
        pageNum: 1,
        pageSize: 1000,
        keyword: ''
      },
      roleList: [], // 全部角色列表
      userRoleList: [] // 用户角色列表
    }
  },
  watch: {
    'setData.isOpen': function (isOpen) {
      if (isOpen) {
        this.getRoleList()
      }
    }
  },
  methods: {
    // 根据用户id获取角色列表
    getRoleListById () {
      getRoleListById(this.setData.id).then((res) => {
        this.userRoleList = res.data
      })
    },
    // 获取全部角色列表
    getRoleList () {
      getRoleList(this.queryInfo).then((res) => {
        this.roleList = res.data.list
        this.getRoleListById()
      })
    },
    // 分配角色
    setUserRole () {
      this.formData = {
        userId: this.setData.id,
        roleIdList: this.userRoleList
      }
      setUserRole(this.formData).then((res) => {
        this.$refs.form.resetFields()
        this.$message({
          message: '分配成功',
          type: 'success'
        })
        this.$emit('successHandle')
        this.closeDialogHandle()
      })
    },
    // 关闭弹窗
    closeDialogHandle () {
      this.setData.isOpen = false
    }
  }
}
</script>
